import { Button, Card, Checkbox, Form, Input, message } from 'antd';
import React, { Component } from 'react';

import styles from './index.module.scss';

import logoSrc from 'asstes/logo.png';
import { loginAPI } from 'api/login';
import { setToken } from 'utils/strorage';

export default class Login extends Component {
  handleFinish = async (values) => {
    try {
      const res = await loginAPI(values);
      // 1. 先缓存token
      setToken(res.data.token);
      // 2. 提示用户
      message.success('登录成功', 1);
      // 3. 跳转路由
      this.props.history.push('/');
    } catch (error) {
      // console.dir是用来打印对象
      console.dir(error);
      // 4.提示用户
      message.warning(error.response.data.message);
    }
  };

  render() {
    return (
      <div className={styles.login}>
        <Card className="login-container" bordered={false}>
          <img className="login-logo" src={logoSrc} alt="" />
          <Form
            onFinish={this.handleFinish}
            initialValues={{
              agerr: true,
              mobile: '13811111111',
              code: '246810',
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '手机号码不能为空',
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入11位手机号码',
                },
              ]}
            >
              <Input placeholder="请输入11位手机号码" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '请输入6位验证码',
                },
              ]}
            >
              <Input placeholder="请输入6位验证码" />
            </Form.Item>

            <Form.Item
              name="agerr"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) => {
                    if (!value) {
                      return Promise.reject(new Error('必须同意协议'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Checkbox>我以阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
